import { Request, Response } from 'express';
import { OrderModel } from '../models/Order';
import OrderSequelize from '../models/OrderSequelize';
import { CartModel } from '../models/Cart';
import { asyncHandler } from '../utils/asyncHandler';
import { ApiResponse } from '../types';
import { OrderQueryParams, CreateOrderRequest, UpdateOrderRequest, OrderStatus, PaymentStatus, ShippingStatus } from '../types/order';

// 获取订单列表
export const getOrders = asyncHandler(async (req: Request, res: Response) => {
  // 处理嵌套在params中的查询参数，与其他接口保持一致
  const queryParams = (req.query as any).params || req.query;
  
  const params = {
    page: parseInt(queryParams.page as string) || 1,
    limit: parseInt(queryParams.limit as string) || 20,
    orderNo: queryParams.orderNo as string,
    userId: queryParams.userId ? parseInt(queryParams.userId as string) : undefined,
    orderStatus: queryParams.orderStatus !== undefined && queryParams.orderStatus !== '' ? parseInt(queryParams.orderStatus as string) : undefined,
    paymentStatus: queryParams.paymentStatus !== undefined && queryParams.paymentStatus !== '' ? parseInt(queryParams.paymentStatus as string) : undefined,
    shippingStatus: queryParams.shippingStatus !== undefined && queryParams.shippingStatus !== '' ? parseInt(queryParams.shippingStatus as string) : undefined,
    startDate: queryParams.startDate && queryParams.startDate !== '' ? queryParams.startDate as string : undefined,
    endDate: queryParams.endDate && queryParams.endDate !== '' ? queryParams.endDate as string : undefined,
    consigneeName: queryParams.consigneeName as string,
    consigneePhone: queryParams.consigneePhone as string,
    sort: queryParams.sort as string || 'createdAt',
    order: (queryParams.order as 'ASC' | 'DESC') || 'DESC'
  };

  const result = await OrderSequelize.findAllWithPagination(params);

  const response: ApiResponse = {
    code: 200,
    message: '获取订单列表成功',
    data: {
      list: result.orders,
      total: result.total,
      page: result.page,
      limit: result.limit,
      totalPages: result.totalPages
    }
  };

  res.json(response);
});

// 获取订单详情
export const getOrderById = asyncHandler(async (req: Request, res: Response) => {
  const { id } = req.params;
  const orderId = parseInt(id);

  if (isNaN(orderId)) {
    const response: ApiResponse = {
      code: 400,
      message: '无效的订单ID'
    };
    return res.status(400).json(response);
  }

  const order = await OrderModel.findById(orderId);

  if (!order) {
    const response: ApiResponse = {
      code: 404,
      message: '订单不存在'
    };
    return res.status(404).json(response);
  }

  const response: ApiResponse = {
    code: 200,
    message: '获取订单详情成功',
    data: order
  };

  res.json(response);
});

// 根据订单号获取订单详情
export const getOrderByNo = asyncHandler(async (req: Request, res: Response) => {
  const { orderNo } = req.params;

  const order = await OrderModel.findByOrderNo(orderNo);

  if (!order) {
    const response: ApiResponse = {
      code: 404,
      message: '订单不存在'
    };
    return res.status(404).json(response);
  }

  const response: ApiResponse = {
    code: 200,
    message: '获取订单详情成功',
    data: order
  };

  res.json(response);
});

// 创建订单
export const createOrder = asyncHandler(async (req: Request, res: Response) => {
  const orderData: CreateOrderRequest = req.body;

  // 验证必填字段
  if (!orderData.userId || !orderData.consigneeName || !orderData.consigneePhone || 
      !orderData.consigneeAddress || !orderData.items || orderData.items.length === 0) {
    const response: ApiResponse = {
      code: 400,
      message: '缺少必填字段'
    };
    return res.status(400).json(response);
  }

  // 计算订单金额
  let goodsAmount = 0;
  for (const item of orderData.items) {
    goodsAmount += item.price * item.quantity;
  }

  const totalAmount = goodsAmount + (orderData.shippingFee || 0) - (orderData.pointsAmount || 0);

  // 生成订单号
  const orderNo = OrderModel.generateOrderNo();

  const orderId = await OrderModel.create({
    ...orderData,
    orderNo,
    totalAmount,
    goodsAmount
  });

  // 如果是从购物车创建订单，删除对应的购物车项
  if (req.body.cartItemIds && req.body.cartItemIds.length > 0) {
    await CartModel.deleteItems(req.body.cartItemIds, orderData.userId);
  }

  const response: ApiResponse = {
    code: 200,
    message: '创建订单成功',
    data: { orderId, orderNo }
  };

  res.json(response);
});

// 更新订单
export const updateOrder = asyncHandler(async (req: Request, res: Response) => {
  const { id } = req.params;
  const orderId = parseInt(id);
  const updateData: UpdateOrderRequest = req.body;

  if (isNaN(orderId)) {
    const response: ApiResponse = {
      code: 400,
      message: '无效的订单ID'
    };
    return res.status(400).json(response);
  }

  const success = await OrderModel.update(orderId, updateData);

  if (!success) {
    const response: ApiResponse = {
      code: 404,
      message: '订单不存在或更新失败'
    };
    return res.status(404).json(response);
  }

  const response: ApiResponse = {
    code: 200,
    message: '更新订单成功'
  };

  res.json(response);
});

// 删除订单
export const deleteOrder = asyncHandler(async (req: Request, res: Response) => {
  const { id } = req.params;
  const orderId = parseInt(id);

  if (isNaN(orderId)) {
    const response: ApiResponse = {
      code: 400,
      message: '无效的订单ID'
    };
    return res.status(400).json(response);
  }

  const success = await OrderModel.delete(orderId);

  if (!success) {
    const response: ApiResponse = {
      code: 404,
      message: '订单不存在或删除失败'
    };
    return res.status(404).json(response);
  }

  const response: ApiResponse = {
    code: 200,
    message: '删除订单成功'
  };

  res.json(response);
});

// 获取订单统计
export const getOrderStats = asyncHandler(async (req: Request, res: Response) => {
  const stats = await OrderModel.getStats();

  const response: ApiResponse = {
    code: 200,
    message: '获取订单统计成功',
    data: stats
  };

  res.json(response);
});

// 支付订单
export const payOrder = asyncHandler(async (req: Request, res: Response) => {
  const { id } = req.params;
  const { paymentMethod } = req.body;
  const orderId = parseInt(id);

  if (isNaN(orderId)) {
    const response: ApiResponse = {
      code: 400,
      message: '无效的订单ID'
    };
    return res.status(400).json(response);
  }

  // 验证支付方式
  if (!paymentMethod || ![1, 2, 3].includes(paymentMethod)) {
    const response: ApiResponse = {
      code: 400,
      message: '无效的支付方式'
    };
    return res.status(400).json(response);
  }

  // 检查订单状态
  const order = await OrderModel.findById(orderId);
  if (!order) {
    const response: ApiResponse = {
      code: 404,
      message: '订单不存在'
    };
    return res.status(404).json(response);
  }

  if (order.orderStatus !== OrderStatus.PENDING_PAYMENT) {
    const response: ApiResponse = {
      code: 400,
      message: '订单状态不允许支付，当前状态：' + getOrderStatusText(order.orderStatus)
    };
    return res.status(400).json(response);
  }

  if (order.paymentStatus === PaymentStatus.PAID) {
    const response: ApiResponse = {
      code: 400,
      message: '订单已支付，无需重复支付'
    };
    return res.status(400).json(response);
  }

  // 模拟支付处理延迟（500-1500ms）
  const delay = Math.random() * 1000 + 500;
  await new Promise(resolve => setTimeout(resolve, delay));

  // 模拟支付结果（98%成功率）
  const isPaymentSuccess = Math.random() > 0.02;

  if (!isPaymentSuccess) {
    const response: ApiResponse = {
      code: 500,
      message: '支付处理失败，请重试'
    };
    return res.status(500).json(response);
  }

  try {
    // 更新订单状态
    const updateSuccess = await OrderModel.update(orderId, {
      paymentStatus: PaymentStatus.PAID,
      orderStatus: OrderStatus.PENDING_SHIPMENT,
      paymentMethod
    });

    if (!updateSuccess) {
      const response: ApiResponse = {
        code: 500,
        message: '支付成功但订单状态更新失败'
      };
      return res.status(500).json(response);
    }

    const response: ApiResponse = {
      code: 200,
      message: '支付成功',
      data: {
        orderId,
        orderNo: order.orderNo,
        paymentMethod,
        totalAmount: order.totalAmount,
        paymentTime: new Date().toISOString()
      }
    };

    res.json(response);
  } catch (error) {
    console.error('支付处理错误:', error);
    const response: ApiResponse = {
      code: 500,
      message: '支付处理异常，请联系客服'
    };
    res.status(500).json(response);
  }
});

// 获取订单状态文本的辅助函数
function getOrderStatusText(status: OrderStatus): string {
  const statusMap = {
    [OrderStatus.PENDING_PAYMENT]: '待付款',
    [OrderStatus.PENDING_SHIPMENT]: '待发货',
    [OrderStatus.PENDING_RECEIPT]: '待收货',
    [OrderStatus.COMPLETED]: '已完成',
    [OrderStatus.CANCELLED]: '已取消',
    [OrderStatus.REFUNDING]: '退款中'
  };
  return statusMap[status] || '未知状态';
}

// 发货
export const shipOrder = asyncHandler(async (req: Request, res: Response) => {
  const { id } = req.params;
  const { deliveryCompany, deliveryNo } = req.body;
  const orderId = parseInt(id);

  if (isNaN(orderId)) {
    const response: ApiResponse = {
      code: 400,
      message: '无效的订单ID'
    };
    return res.status(400).json(response);
  }

  // 检查订单状态
  const order = await OrderModel.findById(orderId);
  if (!order) {
    const response: ApiResponse = {
      code: 404,
      message: '订单不存在'
    };
    return res.status(404).json(response);
  }

  if (order.orderStatus !== OrderStatus.PENDING_SHIPMENT) {
    const response: ApiResponse = {
      code: 400,
      message: '订单状态不允许发货'
    };
    return res.status(400).json(response);
  }

  // 更新订单状态
  await OrderModel.update(orderId, {
    shippingStatus: ShippingStatus.SHIPPED,
    orderStatus: OrderStatus.PENDING_RECEIPT,
    deliveryCompany,
    deliveryNo
  });

  const response: ApiResponse = {
    code: 200,
    message: '发货成功'
  };

  res.json(response);
});

// 确认收货
export const confirmOrder = asyncHandler(async (req: Request, res: Response) => {
  const { id } = req.params;
  const orderId = parseInt(id);

  if (isNaN(orderId)) {
    const response: ApiResponse = {
      code: 400,
      message: '无效的订单ID'
    };
    return res.status(400).json(response);
  }

  // 检查订单状态
  const order = await OrderModel.findById(orderId);
  if (!order) {
    const response: ApiResponse = {
      code: 404,
      message: '订单不存在'
    };
    return res.status(404).json(response);
  }

  if (order.orderStatus !== OrderStatus.PENDING_RECEIPT) {
    const response: ApiResponse = {
      code: 400,
      message: '订单状态不允许确认收货'
    };
    return res.status(400).json(response);
  }

  // 更新订单状态
  await OrderModel.update(orderId, {
    shippingStatus: ShippingStatus.RECEIVED,
    orderStatus: OrderStatus.COMPLETED
  });

  const response: ApiResponse = {
    code: 200,
    message: '确认收货成功'
  };

  res.json(response);
});

// 取消订单
export const cancelOrder = asyncHandler(async (req: Request, res: Response) => {
  const { id } = req.params;
  const orderId = parseInt(id);

  if (isNaN(orderId)) {
    const response: ApiResponse = {
      code: 400,
      message: '无效的订单ID'
    };
    return res.status(400).json(response);
  }

  // 检查订单状态
  const order = await OrderModel.findById(orderId);
  if (!order) {
    const response: ApiResponse = {
      code: 404,
      message: '订单不存在'
    };
    return res.status(404).json(response);
  }

  if (order.orderStatus === OrderStatus.COMPLETED || order.orderStatus === OrderStatus.CANCELLED) {
    const response: ApiResponse = {
      code: 400,
      message: '订单状态不允许取消'
    };
    return res.status(400).json(response);
  }

  // 更新订单状态
  await OrderModel.update(orderId, {
    orderStatus: OrderStatus.CANCELLED
  });

  const response: ApiResponse = {
    code: 200,
    message: '取消订单成功'
  };

  res.json(response);
});